<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="分类名称">
                <a-input placeholder="请输入分类名称" v-model="queryParam.name" allowClear></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button type="primary" @click="getList()">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :border="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <a-radio-group v-model="queryParam.is_show" @change="getList()">
          <a-radio-button v-for="item of statusList" :key="item.id" :value="item.id"> {{ item.name }} </a-radio-button>
        </a-radio-group>
        <div style="display: flex">
          <a-button type="primary" style="margin-right: 10px" @click="edit()">+ 新增</a-button>
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item @click="handleAll('change', '1')">批量开启</a-menu-item>
              <a-menu-item @click="handleAll('change', '0')">批量关闭</a-menu-item>
              <a-menu-item @click="handleAll('remove')">批量删除</a-menu-item>
            </a-menu>
            <a-button> 批量操作 </a-button>
          </a-dropdown>
        </div>
      </div>

      <a-table
        :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
        size="default"
        :columns="columns"
        :data-source="list"
        :row-key="(record) => record.id"
        :pagination="{
          total: this.total,
          pageSize: this.pageSize,
          showSizeChanger: false,
          onChange: this.tablePageChange,
        }"
      >
        <!-- <span slot="pic_url" slot-scope="text, record">
          <div class="pic_url">
            <span v-if="!record.pic_url">暂无</span>
            <img v-else :src="record.pic_url" alt="" />
          </div>
        </span> -->

        <span slot="is_show" slot-scope="text, record">
          <a-tag
            v-if="getStatus(record.is_show)"
            :color="getStatus(record.is_show).color"
            @click="handleItem('change', record)"
          >
            {{ getStatus(record.is_show).statusText }}
          </a-tag>
        </span>

        <span slot="sort" slot-scope="text, record">{{ record.sort }}</span>

        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleItem('edit', record)" size="small">编辑</a-button>
          <a-divider type="vertical" />
          <a-popconfirm title="确认删除该分类吗？" @confirm="handleItem('remove', record)">
            <a-button type="link" size="small">删除</a-button>
          </a-popconfirm>
        </span>
      </a-table>

      <a-modal
        :title="getPopTitle"
        :width="800"
        :confirm-loading="modalLoading"
        :mask-closable="false"
        :destroy-on-close="true"
        v-model="visible"
        @ok="submitForm"
      >
        <a-form-model
          ref="coordinateForm"
          :rules="rules"
          :model="form"
          :labelCol="{ span: 4 }"
          :wrapperCol="{ span: 18 }"
        >
          <a-form-model-item label="分类名称" prop="name">
            <a-input v-model="form.name" />
          </a-form-model-item>

          <!-- <a-form-model-item label="分类图片" prop="pic_url">
            <storage-select v-model="form.pic_url"></storage-select>
          </a-form-model-item> -->

          <a-form-model-item label="排序" prop="sort">
            <a-input-number v-model="form.sort" :min="0" :precision="0" />
          </a-form-model-item>

          <a-form-model-item label="是否显示" prop="is_show">
            <a-radio-group name="radioGroup" v-model="form.is_show">
              <a-radio value="1">是</a-radio>
              <a-radio value="0">否</a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { categoryEdit, categoryList, categoryStatusEdit, categoryRemove } from '@/api/videoClassify'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
  },
  {
    title: '分类名称',
    dataIndex: 'name',
  },
  // {
  //   title: '分类图片',
  //   scopedSlots: {
  //     customRender: 'pic_url'
  //   }
  // },
  {
    title: '排序',
    scopedSlots: {
      customRender: 'sort',
    },
    sorter: (a, b) => a.sort - b.sort,
    scopedSlots: { customRender: 'sort' },
  },
  {
    title: '状态',
    scopedSlots: {
      customRender: 'is_show',
    },
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action',
    },
  },
]
export default {
  data() {
    return {
      statusList: [
        { id: '-1', name: '全部', color: 'blue', statusText: '-' },
        { id: '1', name: '已开启', color: 'green', statusText: '已开启' },
        { id: '0', name: '已关闭', color: 'red', statusText: '已关闭' },
      ],

      // 表头
      columns,

      total: 0,
      pageNo: 1,
      pageSize: 10,
      // 查询参数
      queryParam: {
        name: '',
        is_show: '-1',
      },
      // 数据列表
      list: [],

      visible: false,

      rules: {
        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
        pic_url: [{ required: true, message: '请选择分类图片', trigger: 'blur' }],
        is_show: [{ required: true, message: '请选择', trigger: 'change' }],
      },

      modalLoading: false,

      selectedRowKeys: [],

      form: {
        name: '',
        pic_url: '',
        sort: 0,
        is_show: '1',
      },
    }
  },

  mounted() {
    this.getList()
  },

  computed: {
    getStatus() {
      return (is_show) => {
        let item = this.statusList.find((el) => el.id === is_show)
        return item
      }
    },

    getPopTitle() {
      return !this.form.id ? '新增分类' : '修改分类'
    },
  },

  methods: {
    edit(item) {
      if (item) {
        let { name, pic_url, sort, is_show, id } = item

        this.form = {
          name,
          pic_url,
          sort,
          is_show,
          id,
        }
      } else {
        this.form = {
          name: '',
          pic_url: '',
          sort: 0,
          is_show: '1',
        }
      }

      this.visible = true
    },

    // 获取数据列表
    async getList(pageNo = 1) {
      const hide = this.$message.loading('加载中', 0)
      let { queryParam, pageSize } = this

      const res = await categoryList({
        ...queryParam,
        pageSize,
        pageNo,
      })
      if (res.code == 0) {
        this.selectedRowKeys = []
        let { totalCount, data } = res.data
        this.total = totalCount
        this.list = data
      }
      hide()
    },

    // 分页请求
    tablePageChange(e) {
      this.getList(e)
    },
    // 选中多行
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    // 批量操作
    handleAll(type, status) {
      let { selectedRowKeys, list } = this
      if (!selectedRowKeys.length) {
        this.$message.error('请至少选择一条数据~')
        return
      }

      switch (type) {
        case 'change':
          let newList = list
            .filter((el) => {
              return selectedRowKeys.indexOf(el.id) !== -1 && el.is_show !== status
            })
            .map((el) => el.id)

          if (!newList.length) {
            this.$message.error('请选择符合条件的数据~')
            return
          }

          this.changeStatus('1', newList, status)
          break

        case 'remove':
          this.changeStatus('2', selectedRowKeys, '1')
          break
      }
    },

    // 点击单个
    handleItem(type, item) {
      switch (type) {
        case 'change':
          let is_show = '1'
          if (item.is_show === '1') {
            is_show = '0'
          }
          this.changeStatus('1', [item.id], is_show)
          break

        case 'edit':
          this.edit(item)
          break

        case 'remove':
          this.changeStatus('2', [item.id], '1')
          break
      }
    },

    // 修改状态
    changeStatus(type, id, status) {
      categoryStatusEdit({
        id,
        type,
        status,
      }).then((res) => {
        if (res.code !== 0) {
          this.$error({
            content: res.msg,
          })
        } else {
          this.$message.success(res.msg)

          if (type === '1') {
            if (id.length > 1) {
              this.getList()
            } else {
              let idItem = id[0],
                item = this.list.find((el) => el.id === idItem)

              if (item) {
                this.$set(item, 'is_show', status)
              }
            }
          } else {
            this.list = this.list.filter((el) => id.indexOf(el.id) === -1)
            this.totalCount -= id.length
            if (!this.list.length) {
              this.getList()
            }
          }

          this.selectedRowKeys = []
        }
      })
    },

    // 表单提交
    submitForm() {
      this.$refs.coordinateForm.validate((valid) => {
        if (valid) {
          this.modalLoading = true

          let { form, list } = this
          categoryEdit(form)
            .then((res) => {
              this.modalLoading = false

              if (res.code !== 0) {
                this.$error({
                  content: res.msg,
                })
              } else {
                let successMsg = '新增分类成功!'
                if (form.id) {
                  successMsg = '分类修改成功!'
                  let item = list.find((el) => el.id === form.id)

                  this.$set(item, 'name', form.name)
                  this.$set(item, 'pic_url', form.pic_url)
                  this.$set(item, 'sort', form.sort)
                  this.$set(item, 'is_show', form.is_show)
                } else {
                  this.getList()
                }
                this.$message.success(successMsg)
                this.visible = false
              }
            })
            .catch((err) => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
.searchBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  padding: 8px 0 18px 0;
  /deep/ .ant-input-affix-wrapper {
    width: 220px;
    margin-right: 20px;
  }
  .select {
    display: flex;
    align-items: center;
    margin-right: 20px;
  }
}

::v-deep {
  .ant-tag {
    cursor: pointer;
  }
}

.pic_url {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;

  img {
    width: 100%;
    height: 100%;
  }
}
</style>
